define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
     require('echarts/chart/pie');
    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');

    var product=['精准','置顶','智能','刷新','简历','品牌广告','频道合作','联盟','品牌KA','其他'];
    var cache={};

    var productName={
    	"zhineng":"智能",
    	"jingzhun":"精准",
    	"zhiding":"置顶",
    	"all":"总体"
    };

     var chart_pie = ec.init(document.getElementById('pie'));

    var chart_bar1=ec.init(document.getElementById('bar1'));

    var chart_bar2=ec.init(document.getElementById('bar2'));

//饼图的数据模版
var option_pie_one=    {
	title : {
                text: '',
                x:'center',
                y:'380'
            },
        tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        x : 'left',
        data:product
    },
        calculable : false ,
    series : [
        {
            name:'',
            type:'pie',
            radius : [0, 50],
            center:['45%','50%'],
            itemStyle : {
                normal : {
                    label : {
                        position : 'inner'
                    },
                    labelLine : {
                        show : false
                    }
                }
            },
            data:[]
        },
        {
            name:'',
            center:['45%','50%'],
            type:'pie',
            radius : [65, 95],
            data:[]
        }
    ]
    };

 //带timeline的饼图模版   
var option_pie = {
    timeline : {
            type:"number",
    symbolSize:3,
        x:"1%",
        x2:"1%",
        width:"100%",
        label:{
                interval: 'auto',
                                formatter:function(param){
                        var dateGrp = $('#totalOption').attr('dateGrp');
    if(dateGrp=='quarter'){
    return param.substr(0,4)+"Q"+param.substr(5,1);
    }
            return param;
        }
        },
        data : ['']
    },
    options:[]
};

var option_bar2 = {
    timeline : {
    	show:false,
        data : ['']
    },
    options:[]
};

var option_bar2_one = {
	title : {
                text: '差额百分比',
                link:'http://wiki.58corp.com/index.php?title=%E6%94%B6%E5%85%A5%E7%9C%8B%E6%9D%BF%E6%8C%87%E6%A0%87',
                subtext:'',
                                subtextStyle:{
                	color:'blue'
                }
            },
    tooltip : {
        trigger: 'axis',
        formatter:"{b}<br>差额百分比：{c}%"
    },
    // legend: {
    //     data:cate
    // },
    calculable : true,
    xAxis : [
        {
            type : 'category',
            data : function(){
                var ss= product.concat([]);
                ss.unshift('总体');
                return ss;
            }()
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'',
            type:'bar',
            itemStyle : { normal: {color:'#F3A43B',label : {show: false, position: 'top'}}},
            data:[],
        }
    ]
};

var option_bar1_one = {
	title : {
                text: '预估完成率',
                link:'http://wiki.58corp.com/index.php?title=%E6%94%B6%E5%85%A5%E7%9C%8B%E6%9D%BF%E6%8C%87%E6%A0%87',
                subtext:'',
                                subtextStyle:{
                	color:'blue'
                }
            },
        legend: {
        data:['预估','实际','总体时间','当前时间'],
        selectedMode:false
    },
    tooltip : {
        trigger: 'axis',
        formatter:function(param){
            // console.log(param);
           var result=param[0][1]+"<br>";
           result+=param[1].seriesName+"："+param[1].value+"%<br>";
           result+=param[0].seriesName+"："+((Number(param[0].value)+Number(param[1].value)).toFixed(2))+"%";
           return result;            
        }
    },
    calculable : true,
    yAxis : [
        {
            type : 'value',
            splitNumber:2
        }
    ],
    xAxis : [
        {
            type : 'category',
            data :function(){
                var ss= product.concat([]);
                ss.unshift('总体');
                return ss;
            }()
            // axisLabel:{
            // 	margin:2,
            // 	textStyle:{
            // 		fontSize:1
            // 	}
            // }
        }
    ],
    series : [
            {
            name:'实际',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'gray',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            },
            data:[{
                value:'',
                itemStyle: {
                normal: {
                    color: 'gray',
                    barBorderColor: '#B5C334',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            }
            }]
        },
        {
            name:'预估',
            type:'bar',
            stack: 'sum',
            itemStyle: {
                normal: {
                    color: 'tomato',
                    barBorderColor: 'tomato',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            },
            data:[{
                value:'',
                itemStyle: {
                normal: {
                    color: '#B5C334',
                    barBorderColor: '#B5C334',
                    barBorderWidth: 6,
                    barBorderRadius:0
                }
            }
            }]
        },
        {
                name:'总体时间',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                [
         {name: '',yAxis:100,xAxis:-1},           
        {name: '',yAxis:100,xAxis:10}
                ]
                ]
            }
        },
                {
                name:'当前时间',
                type:'line',
                symbol:'none',
                data:[0],
            markLine: {
                            clickable:false,
                data: [
                                [
         {name: '',value:'',yAxis:0,xAxis:-1},                               
        {name: '',value:'',yAxis:0,xAxis:10}

                ]
                ]
            }
        }
    ]
};


// var pieTableHead_month='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当月任务</th><th>实际进度</th><th>完成所需日均额度</th><th>当前实际日均收入</th><th>差额百分比</th><th>预估完成率</th></tr>';
// var pieTableHead_quarter='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当季度任务</th><th>实际进度</th><th>完成所需日均额度</th><th>当前实际日均收入</th><th>差额百分比</th><th>预估完成率</th></tr>';

var pieTableHead_month='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当前实际日均收入</th></tr>';
var pieTableHead_quarter='<tr role="row"><th>业务线</th><th>实际完成</th><th>环比</th><th>同比</th><th>当前实际日均收入</th></tr>';

//显示某个时间的饼图详细数据
function showPieDetail(time){
    if(!cache){
        console.log("无缓存数据");
    }
    var data=cache.options[time];
        var dataSort=sortByName(data);

    $('#pieDetail thead').text("");
    var dateGrp = $('#totalOption').attr('dateGrp');
    if(dateGrp=='month'){
    $('#pieDetail thead').append(pieTableHead_month);
    }else if (dateGrp=='quarter') {
        $('#pieDetail thead').append(pieTableHead_quarter);
    };

        $('#pieDetail tbody').text("");
                    $.each(dataSort,function(index,value){
                    $('#pieDetail tbody').append("<tr></tr>");
                    $('#pieDetail tbody tr:last').append(addInfo(value.productTypeName));
                    $('#pieDetail tbody tr:last').append(addInfo(value.cash));
                    $('#pieDetail tbody tr:last').append(addInfo(value.cash_chain));
                    $('#pieDetail tbody tr:last').append(addInfo(value.cash_YOYO));
                    // $('#pieDetail tbody tr:last').append(addInfo(value.task));
                    // $('#pieDetail tbody tr:last').append(addInfo4(value));                     
                    // $('#pieDetail tbody tr:last').append(addInfo(value.avg_task));
                     $('#pieDetail tbody tr:last').append(addInfo(value.avg_complete));
                     // $('#pieDetail tbody tr:last').append(addInfo2(-value.avg_bal));
                     // $('#pieDetail tbody tr:last').append(addInfo3(value.fore_rate));
                    });

}

function addInfo4(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value.complete_rate)){
        var ss=value.complete_rate+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if((value.complete_rate-value.time_rate*100)>0){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value.complete_rate));
        }
    }
    return td.html(value.complete_rate);
}

function addInfo3(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if(value>100){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value));
        }
    }
    return td.html(value);
};

function addInfo2(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
            if (value==0) {
                return td.html(ss);
            };
            if(value>0){
                td.addClass('text-danger');
                td.html(ss);
            }else{
                td.addClass('text-success');
                td.html(ss);
            }
            return td;

    }
    return td.html(value);
};

function addInfo(value){
    var td= $('<td></td>');
    //数字
    if(!isNaN(value)){
        var ss=value+"%";
        if(ss.indexOf('.')!=-1){
            if (value==0) {
                return td.html(ss);
            };
            if(value>0){
                td.addClass('text-danger');
                td.html(ss);
                td.append('<i class="upi"></i>');
            }else{
                td.addClass('text-success');
                td.html(ss);
                td.append('<i class="downi"></i>');
            }
            return td;
        }else{
             return td.html(zrnumber.addCommas(value));
        }
    }
    return td.html(value);
}

var temp=['总体','精准','置顶','智能','联盟','刷新','简历','频道合作','品牌广告','品牌KA','其他'];
function sortByName(data){
    if(!data)return [];
    var aa={};
    $.each(data,function(index,value){
        aa[value.productTypeName]=value;
    });
    var resut=[];
    $.each(temp,function(index,value){
        resut.push(aa[value]);
    });
    return resut;
}

         function formatShowDate(yyyymmdd){
        var dateGrp = $('#totalOption').attr('dateGrp');
        if('day'==dateGrp){
            return yyyymmdd.substr(0,4)+"-"+yyyymmdd.substr(4,2)+"-"+yyyymmdd.substr(6,2);
        }else if('quarter'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(5,1)+"季度";
        }else if('month'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
}


//设置饼图数据
function setPie(data){
                    option_pie.options=[];
                    //饼图时间轴
                    option_pie.timeline.data=data.timeline;
                    option_pie.timeline.currentIndex=data.timeline.length-1;
                    //饼图数据
                    $.each(data.options,function(index,value){
                        var option= zrUtil.clone(option_pie_one);
                        option.series[0].name=index;
                        option.series[1].name=index;
                        $.each(value,function(i,v){
                            if(v.productTypeName=='总体'){
                                 option.series[0].data.push({"name":v.productTypeName,"value":v.cash});
                            }else{
                                option.series[1].data.push({"name":v.productTypeName,"value":v.cash});
                            }
                        });
                        option.title.text=formatShowDate(index);
                        option_pie.options.push(option);
                    });
                     chart_pie.setOption(option_pie,true);
                     chart_pie.hideLoading();
                     showPieDetail(data.timeline[data.timeline.length-1]);
}

// 设置右下角柱状图
function setBar2(data){
                    option_bar2.options=[];
                    //柱形图时间轴
                    option_bar2.timeline.data=data.timeline;
                    option_bar2.timeline.currentIndex=data.timeline.length-1;
                    //柱形图数据
                    $.each(data.options,function(time,value){
                        var option=zrUtil.clone(option_bar2_one);
                         option.title.subtext=formatShowDate(time);
                         var obj=sortByProduct(value);
                    $.each(option.xAxis[0].data,function(index,value_in){
                        if(!obj[value_in]){
                            option.series[0].data.push(0);
                        }else{
                            if (value_in=='总体') {
                                option.series[0].data.push({value:-obj[value_in].avg_bal,itemStyle:{normal:{color: '#B5C334'}}});
                            }else{
                                option.series[0].data.push(-obj[value_in].avg_bal);
                            }
                        }
                    });
                        option_bar2.options.push(option);
                    });
                    chart_bar2.setOption(option_bar2,true);
                    chart_bar2.hideLoading();
}

function sortByProduct(list){

                 var obj={};
             $.each(list,function(index,value){
                obj[value.productTypeName]=value;
             });
             return obj;
}

//设置右上角多个柱状图
function setBar1(data){

            var option=zrUtil.clone(option_bar1_one)
            //取最后一个
             var name=data.timeline[data.timeline.length-1];

             option.title.subtext='数据截止日期('+data.options[name][0].stat_date+')';

             var obj=sortByProduct(data.options[name]);

             $.each(option.xAxis[0].data,function(i,v){
                if(!obj[v])return;
                if(v=='总体'){
                    option.series[0].data[0].value=obj[v].complete_rate;
                    option.series[1].data[0].value=(obj[v].fore_rate-obj[v].complete_rate).toFixed(2);
                }else{
                option.series[0].data.push(obj[v].complete_rate);
                option.series[1].data.push((obj[v].fore_rate-obj[v].complete_rate).toFixed(2));
                }

             });

                    var time=(data.options[name][0].time_rate*100).toFixed(2);
                    option.series[3].markLine.data[0][0].yAxis=time;
                    option.series[3].markLine.data[0][1].yAxis=time;
                     option.series[3].markLine.data[0][0].value=time;
             // option.series.push({"name":"完成","type":"bar","data":data.options[name].complete_rate});
             // option.series.push({"name":"预期","type":"bar","data":data.options[name].fore_rate});
             chart_bar1.setOption(option);
             chart_bar1.hideLoading();

}


function showPie(type){
    chart_pie.showLoading({
            text: '正在努力的读取数据中...'
    });
    // chart_bar1.showLoading({
    //         text: '正在努力的读取数据中...'
    // });
    // chart_bar2.showLoading({
    //         text: '正在努力的读取数据中...'
    // });
    $.ajax({
        url: '/dashboard/income/ajax/getKpiByOnline',
        type: 'POST',
        async: true,
        data:{"type":type},
        dataType: 'json',
        success: function(data) {
            cache=data;
            // console.log(data);
            //设置饼图
            setPie(data);
            // setBar1(data);
            // setBar2(data);
            // chart_pie.connect(chart_bar2);
            // chart_bar2.connect(chart_pie);

             //timeline联动
             chart_pie.on("timelineChanged", function(param){
                showPieDetail(param.data);
                // chart_bar2.component.timeline.play(param.currentIndex,false);
             });
            
        },
        timeout: 30000,
        error: function() {
        }
    });
}

    var returnObj={
        showPie:showPie
    };
    return returnObj;
});